<template>
  <div class="map-container">
    <div class="box">
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      <div class="map" id="map"></div>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { onMounted, ref, inject } from 'vue';

let $echart = inject('echarts');
let mapData = ref(null);
let provinceData = ref([]);

// 获取地图数据
async function fetchMapData() {
  try {
    const instance = axios.create();
    const response = await instance.get('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json', {
      headers: {}
    });
    mapData.value = response.data;
  } catch (error) {
    console.error('Failed to fetch map data:', error);
  }
}

// 获取省份数据
async function fetchProvinceData() {
  try {
    const response = await axios.get('http://localhost:7000/service-nepm/administrator/getProvinceMesg');
    provinceData.value = response.data;
  } catch (error) {
    console.error('Failed to fetch province data:', error);
  }
}

// 动态颜色生成函数
function getAreaColor(value, min, max) {
  const percent = (value - min) / (max - min);
  const startColor = [204, 204, 204]; // 灰色 RGB
  const endColor = [157, 41, 51]; // 红色 RGB
  const color = startColor.map((part, index) => {
  const mix = Math.round(part + percent * (endColor[index] - part));
  return mix;
  });
  return `rgb(${color.join(',')})`;
}

// 计算省份的中心点
function getProvinceCenter(geometry) {
  let [minX, minY, maxX, maxY] = [Infinity, Infinity, -Infinity, -Infinity];
  geometry.coordinates[0][0].forEach(([lng, lat]) => {
    if (lng < minX) minX = lng;
    if (lat < minY) minY = lat;
    if (lng > maxX) maxX = lng;
    if (lat > maxY) maxY = lat;
  });
  return [(minX + maxX) / 2, (minY + maxY) / 2];
}

onMounted(async () => {
  await Promise.all([fetchMapData(), fetchProvinceData()]);
  if (mapData.value && provinceData.value) {
    let minAqi = Math.min(...provinceData.value.map(item => item.AQI_count));
    let maxAqi = Math.max(...provinceData.value.map(item => item.AQI_count));
    let seriesData = provinceData.value.map(item => {
      const feature = mapData.value.features.find(f => f.properties.name === item.province_name);
      if (feature) {
        const center = getProvinceCenter(feature.geometry);
        return {
          name: item.province_name,
          value: [...center, item.AQI_count]//中心点
        };
      }
    }).filter(item => item !== undefined);//过滤

    let myChart = $echart.init(document.getElementById('map'));
    $echart.registerMap('china', mapData.value);

    let option = {
      title: {
        text: '-- 全国省份AQI覆盖率(%) --',
        left: 'center',
        top: '20',
        textStyle: {
          color: '#fff',
          fontSize: 18,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: function (params) {
          console.log(params);
          // 确保 tooltip 能正确显示数据
          if (params.data && params.data.value && params.data.value.length > 2) {
            console.log(params.data.value[2]);
            return `AQI超标数: ${params.data.value[2]}`;
          } else {
            return `${params.name}: No data`;
          }
        },
        backgroundColor: 'rgba(50,50,50,0.7)',
        borderColor: '#7f7f7f',
        borderWidth: 1,
        textStyle: {
          color: '#fff'
        }
      },
      geo: {
        map: 'china',
        zoom: 1.7,
        roam: true,
        center: [104.5, 36],
        itemStyle: {
          normal: {
            borderColor: '#389BB7',
            shadowBlur: 15,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        regions: mapData.value.features.map(feature => {
          const aqi = provinceData.value.find(item => item.province_name === feature.properties.name)?.AQI_count || 0;
          return {
            name: feature.properties.name,
            itemStyle: {
              areaColor: getAreaColor(aqi, minAqi, maxAqi)
            }
          };
        })
      },

      series: [
        {
          name: 'AQI',
          type: 'scatter',
          coordinateSystem: 'geo',
          data: seriesData,
          symbolSize: 12,
          itemStyle: {
            color: 'rgb(255, 215, 0)',
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.8)'
          }
        }
      ]
    };

    myChart.setOption(option);
  }
});
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 66%;
  margin: 20px auto;
  border-radius: 15px;
  overflow: hidden;
}

.map {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 1;
}

.box {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow: hidden;
  border: 2px solid #2a3cad;
  color: white;
}

.box span {
  position: absolute;
  width: 100%;
  height: 100%;
  display: block;
  box-sizing: border-box;
}

.box span:nth-child(1) {
  transform: rotate(0deg);
}

.box span:nth-child(3) {
  transform: rotate(180deg);
}

.box span:before {
  content: '';
  position: absolute;
  width: 100%;
  height: 2px;
  background: #50dfdb;
  animation: animate 4s linear infinite;
}

@keyframes animate {
  0% {
    transform: scaleX(0);
    transform-origin: left;
  }
  50% {
    transform: scaleX(1);
    transform-origin: left;
  }
  50.1% {
    transform: scaleX(1);
    transform-origin: right;
  }
  100% {
    transform: scaleX(0);
    transform-origin: right;
  }
}
</style>
